const express = require('express');
const router = express.Router();
const projectClone = require('../script/projectClone')
const projectBuild = require('../script/projectBuild')
const { UploadApplet } = require('../script/uploadApplet')
const getWxConfig  = require('../script/getWxConfig')
const { trialTemplate } = require('../script/markdownTemplate')
const { sendMarkdown, sendPicture } = require('../script/wxRobot')
const chalk = require('chalk')
const createQrCode = require('../script/qrCode');

router.post('/gitee-webhooks', (req, res, next) => {
  // 拉取远程项目到本地
  let clonePath = projectClone(req.body)
  if (!clonePath) {
    return res.json(req.body)
  }

  // 构建项目获取打包后的项目实际路径
  let actualProjectPath = projectBuild(clonePath)

  // 获取上传参数
  const wxConfig = getWxConfig(actualProjectPath, req.body)

  // 上传小程序体验版
  const uploadApplet = new UploadApplet(wxConfig)
  uploadApplet.upload().then(res => {

    // 发送上传成功信息到企业微信群机器人中
    sendMarkdown(trialTemplate({
      name: wxConfig.name,
      user: wxConfig.user,
      branch: wxConfig.branch,
      version: wxConfig.version,
      desc: wxConfig.desc,
      time: new Date().toLocaleString(),
    })).then(() => {
      console.log(chalk.greenBright('信息发送成功'));
      createQrCode(`https://open.weixin.qq.com/sns/getexpappinfo?appid=${wxConfig.appid}&path=pages%2Fmain%2Fmain.html#wechat-redirect`, (path) => {
          sendPicture(path);
        },
      );
    })
  })

  res.json(req.body)
});

module.exports = router;
